package com.qf.utils;

import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.*;

/**
 * @Author ztf
 * @Date 16:35 2021/12/28
 **/
public class Md5Utils {

    //转换字符集合
    private static String character = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789";
    private static List characters = new ArrayList();

    static {
        char[] chars = character.toCharArray();
        System.err.println(Arrays.toString(chars));
        for (char aChar : chars) {
            characters.add(aChar);
        }
    }

    /**
     * 随机生成指定长度的字符串
     * @param size 长度
     * @return 生成的字符串
     */
    public static String getRandomString(int size) {
        //打乱字符集合
        Collections.shuffle(characters);
        Random random = new Random();
        StringBuffer stringBuffer = new StringBuffer();
        for (int i = 0; i < size; i++) {
            int index = random.nextInt(characters.size());
            stringBuffer.append(characters.get(index).toString());
        }
        return stringBuffer.toString();
    }

    /**
     *根据盐与迭代次数生成MD5值
     * @param str 字符串
     * @param salt 盐
     * @param times 迭代次数
     * @return MD5值
     */
    public static String getMd5(String str, String salt, int times) {
        if (times==1){
            return DigestUtils.md5DigestAsHex((salt+str+salt).getBytes(StandardCharsets.UTF_8));
        }else {
            --times;
            return getMd5(getMd5(str, salt, times), salt, times);
        }
    }
}
